<template>
  <div class="overflow-x-hidden w-full">
    <div class="flex justify-between items-center py-4">
      <h2 class="text-2xl">课程管理</h2>
      <div class="flex gap-2 mx-2">
        <ZButton
          icon-class="icon-[mdi--restart]"
          color="secondary"
          size="sm"
          @click="refetch"
          :loading="isLoading"
        >
          刷新
        </ZButton>
        <ZButton
          icon-class="icon-[mdi--add]"
          color="primary"
          size="sm"
          @click="
            selected = undefined;
            courseShow = true;
          "
        >
          添加课程
        </ZButton>
      </div>
      <ZModal box-class="" v-model="courseShow" @success="courseShow = false">
        <h3>{{ selected ? "编辑课程" : "添加课程" }}</h3>
        <CourseForm
          :init-values="selected"
          @success="courseShow = false"
        ></CourseForm>
      </ZModal>
    </div>

    <ZTable
      class="border rounded-box hidden md:table"
      :columns="columns"
      :data="results || []"
      key-name="id"
    >
      <template #name="{ row }">
        <RouterLink class="link text-primary" :to="`/course/${row.id}`">{{
          row.name
        }}</RouterLink>
      </template>
      <template #nature="{ row }">
        <div class="flex items-center gap-2">
          <span class="">{{ row.nature }}</span>
          <span class="badge badge-soft badge-accent">{{
            row._count?.reports
          }}</span>
        </div>
      </template>
      <template #action="{ row }">
        <ZButton
          icon-class="icon-[mdi--edit]"
          color="primary"
          size="sm"
          @click="
            selected = row;
            courseShow = true;
          "
        >
          编辑
        </ZButton>
        <ZButton
          class="mx-2"
          icon-class="icon-[mdi--arrow-left-bottom]"
          color="success"
          size="sm"
          @click="$router.push(`/course/${row.id}`)"
        ></ZButton>
        <ZButton
          icon-class="icon-[mdi--delete]"
          modifier="circle"
          color="error"
          size="sm"
          :loading="isDeleting"
          @click="onDelete(row)"
        >
        </ZButton>
      </template>
    </ZTable>

    <div class="grid grid-cols-1 gap-4 p-2 md:hidden">
      <ZCard
        v-for="row in results"
        :key="row.id"
        class="card bg-base-100 shadow-lg border border-primary"
      >
        <h3 class="card-title">
          <RouterLink class="link text-primary" :to="`/course/${row.id}`">
            {{ row.name }}
          </RouterLink>
          <div
            class="flex gap-2 items-center badge badge-accent badge-soft border border-primary"
          >
            <span>{{ row.nature }}</span>
            <span class="font-mono"> {{ row._count?.reports }}</span>
          </div>
        </h3>
        <div class="grid grid-cols-4 gap-2 text-sm">
          <div>
            <div class="text-base-content/60">教师</div>
            <div>{{ row.teacher }}</div>
          </div>
          <div>
            <div class="text-base-content/60">学年</div>
            <div>{{ row.semester }}</div>
          </div>
          <div>
            <div class="text-base-content/60">学期</div>
            <div>{{ row.term }}</div>
          </div>
          <div>
            <div class="text-base-content/60">教室</div>
            <div>{{ row.classroom }}</div>
          </div>
        </div>
        <div class="card-actions justify-end mt-4">
          <ZButton
            icon-class="icon-[mdi--edit]"
            color="primary"
            size="sm"
            @click="
              selected = row;
              courseShow = true;
            "
          >
            编辑
          </ZButton>
          <ZButton
            class="mx-2"
            icon-class="icon-[mdi--arrow-left-bottom]"
            color="success"
            size="sm"
            @click="$router.push(`/course/${row.id}`)"
          >
            详情
          </ZButton>
          <ZButton
            icon-class="icon-[mdi--delete]"
            color="error"
            size="sm"
            :loading="isDeleting"
            @click="onDelete(row)"
          >
            删除
          </ZButton>
        </div>
      </ZCard>
    </div>
    <ZPagination
      class="my-4 justify-end"
      :buttons="['first', 'last']"
      :total="count"
      v-model:page="pageParams.page"
      v-model:page-size="pageParams.pageSize"
    />
  </div>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import ZTable, { type TableColumn } from "@/components/ui/ZTable.vue";
import { deleteCourse } from "@/apis/course";
import ZButton from "@/components/ui/ZButton.vue";

import { useMutation, useQueryCache } from "@pinia/colada";
import type { Course } from "@/stores";
import { useFindCourses, COURSE_QUERY_KEY } from "@/query/course";
import ZModal from "@/components/ui/ZModal.vue";
import ZPagination from "@/components/ui/ZPagination.vue";
import ZCard from "@/components/ui/ZCard.vue";

import CourseForm from "./components/CourseForm.vue";

const courseShow = ref(false);

const columns: TableColumn[] = [
  {
    label: "课程名称",
    name: "name",
  },
  {
    label: "教师",
    name: "teacher",
  },
  {
    label: "学年",
    name: "semester",
  },
  {
    label: "学期",
    name: "term",
  },
  {
    label: "教室",
    name: "classroom",
  },
  {
    label: "课程性质",
    name: "nature",
  },
  {
    label: "操作",
    name: "action",
  },
];
const { isLoading, refetch, data, pageParams } = useFindCourses();

const count = computed(() => data.value?.query?.count || 0);
const results = computed(() => data.value?.query?.results || []);

// function onSuccess(value: any) {
//   courseShow.value = false;
//   if (selected.value) results.value = results.value.map(i => i.id !== selected.value?.id ? i : value)
//   else results.value.unshift(value);
// }

const selected = ref<Course>();
const queryCache = useQueryCache();
// 删除课程
const { isLoading: isDeleting, mutate: deleteCourseMutate } = useMutation({
  mutation: deleteCourse,
  onSuccess: (data) => {
    if (data.success) {
      queryCache.invalidateQueries({ key: COURSE_QUERY_KEY.root });
      // const prev = queryCache.getQueryData<ApiResponse<Course>>(
      //   COURSE_QUERY_KEY.list(pageParams.value)
      // );
      // if (prev)
      // queryCache.setQueryData<ApiResponse<Course>>(
      //   COURSE_QUERY_KEY.list(pageParams.value),
      //   {
      //     ...prev,
      //     query: {
      //       ...prev?.query,
      //       count: prev?.query?.count! - 1,
      //       results: prev?.query?.results?.filter(i => i.id !== variables) as Course[],
      //     }
      //   }
      // )
    }
  },
});
async function onDelete(row: Course) {
  if (confirm("确认删除吗？")) {
    deleteCourseMutate(row.id);
  }
}
</script>
